package com.ryan.mdp.config;

import java.util.Set;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.ryan.mdp.reference.MdpReferenceFactoryBean;

public class MdpReferenceBeanDefinationParser extends AbstractMdpBeanDefinationParser {

    private static final String TIMEOUT_ATTRIBUTE = "timeout";
    private static final String SOURCE_ATTRIBUTE = "source";

    @Override
    protected void doParseSpecial(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
        builder.getRawBeanDefinition().setBeanClass(MdpReferenceFactoryBean.class);
        String timeout = element.getAttribute(TIMEOUT_ATTRIBUTE);
        if (!"".equals(timeout)) {
            builder.addPropertyValue(TIMEOUT_ATTRIBUTE, timeout);
        }
        String source = element.getAttribute(SOURCE_ATTRIBUTE);
        if (!"".equals(source)) {
            builder.addPropertyValue(SOURCE_ATTRIBUTE, source);
        }

        NodeList nl = element.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node instanceof Element) {
                Element subElement = (Element) node;
                String name = subElement.getLocalName();
                // mdp:destinations
                if (parseDestinations(element, subElement, parserContext, builder))
                    ;
                else if (BeanDefinitionParserDelegate.DESCRIPTION_ELEMENT.equals(name)) {
                    builder.getRawBeanDefinition().setDescription(subElement.getTextContent());
                }
            }
        }
    }

    @SuppressWarnings("rawtypes")
    protected boolean parseDestinations(Element parent, Element element, ParserContext parserContext,
            BeanDefinitionBuilder builder) {
        String name = element.getLocalName();
        // mdp:destinations
        if (DESTINATIONS.equals(name)) {
            // check shortcut on the parent
            if (parent.hasAttribute(DESTINATION_ATTRIBUTE)) {
                parserContext.getReaderContext().error(
                        "either 'destination' attribute or <destinations> sub-element has be specified", parent);
            }
            Set interfaces = parsePropertySetElement(parserContext, element, builder.getBeanDefinition());
            builder.addPropertyValue(DESTINATIONS, interfaces);
            return true;
        }
        return false;
    }

    @SuppressWarnings("rawtypes")
    protected Set parsePropertySetElement(ParserContext context, Element beanDef, BeanDefinition beanDefinition) {
        return context.getDelegate().parseSetElement(beanDef, beanDefinition);
    }
}
